package com.quectel.cms.controller.alarm;


import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.alarm.dto.AlarmEventConfigDto;
import com.quectel.core.module.alarm.dto.AlarmLinkageRuleDto;
import com.quectel.core.module.alarm.service.AlarmEventConfigService;
import com.quectel.core.module.alarm.service.AlarmLinkageRuleService;
import com.quectel.core.module.device.dto.DeviceCommandTemplateDto;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceCommandTemplateService;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jodd.util.StringUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-10-19 13:39:29
 */
@RestController
@RequestMapping("alarmLinkageRule")
@Tag(name = "AlarmLinkageRuleController", description = "告警规则联动相关api")
public class AlarmLinkageRuleController extends BaseController {

    @DubboReference
    private AlarmLinkageRuleService alarmLinkageRuleService;
    @DubboReference
    private AlarmEventConfigService alarmEventConfigService;
    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private DeviceCommandTemplateService deviceCommandTemplateService;


    /**
     * 列表
     */
    @GetMapping("queryCommands")
    @Operation(summary = "通过条件查询绑定的联动指令列表")
    public Response<List<DeviceCommandTemplateDto>> list(
            @Parameter(description = "设备id") @RequestParam Long deviceId
    ) {


        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        DeviceDto deviceDto = deviceService.selectById(deviceId);
        request.getParams().put("deviceTypeId", deviceDto.getDeviceTypeId());

        return Response.<List<DeviceCommandTemplateDto>>ok().wrap(deviceCommandTemplateService.queryList(request.getParams()));
    }

    /**
     * 列表
     */
    @GetMapping("queryAlarmEventConfigs")
    @Operation(summary = "通过条件查询告警事件配置列表")
    public Response<List<AlarmEventConfigDto>> queryAlarmEventConfigs(
            @Parameter(description = "设备id") @RequestParam Long deviceId
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        DeviceDto deviceDto = deviceService.selectById(deviceId);
        request.getParams().put("deviceTypeId", deviceDto.getDeviceTypeId());

        return Response.<List<AlarmEventConfigDto>>ok().wrap(alarmEventConfigService.queryList(request.getParams()));
    }

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "alarmLinkageRule:list")
    @Operation(summary = "告警规则联动的分页查询列表")
    public Response<Page<AlarmLinkageRuleDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "每页多少条") @RequestParam(required = false) String imei,
            @Parameter(description = "每页多少条") @RequestParam(required = false) String linkageImei
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        Long tenantId = SessionHolder.getSysUser().getTenantId();

        if (StringUtil.isNotEmpty(imei)) {
            DeviceDto deviceDto = deviceService.selectCacheByImei(imei, tenantId);
            if (deviceDto == null) {
                request.getParams().put("deviceId", String.valueOf(SystemConstants.ABNORMAL));
            } else {
                request.getParams().put("deviceId", String.valueOf(deviceDto.getId()));
            }
        }
        if (StringUtil.isNotEmpty(linkageImei)) {
            DeviceDto deviceDto = deviceService.selectCacheByImei(linkageImei, tenantId);
            if (deviceDto == null) {
                request.getParams().put("linkageDeviceId", String.valueOf(SystemConstants.ABNORMAL));
            } else {
                request.getParams().put("linkageDeviceId", String.valueOf(deviceDto.getId()));

            }
        }

        int total = alarmLinkageRuleService.queryTotal(request.getParams());

        List<AlarmLinkageRuleDto> list = null;
        if (total > 0) {
            list = alarmLinkageRuleService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<AlarmLinkageRuleDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<AlarmLinkageRuleDto>>ok().wrap(page);
    }


    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "alarmLinkageRule:info")
    @Operation(summary = "查询单条告警规则联动记录")
    public Response<AlarmLinkageRuleDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (alarmLinkageRuleService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        AlarmLinkageRuleDto alarmLinkageRuleDto = alarmLinkageRuleService.selectById(id);

        return Response.<AlarmLinkageRuleDto>ok().wrap(alarmLinkageRuleDto);
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "alarmLinkageRule:edit")
    @Operation(summary = "保存单条告警规则联动记录")
    @Log(express = "新增联动规则")
    public Response<Object> save(@RequestBody @Validated AlarmLinkageRuleDto alarmLinkageRuleDto) {

        //填充基础数据
        fillSaveCommonData(alarmLinkageRuleDto);

        alarmLinkageRuleService.save(alarmLinkageRuleDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "alarmLinkageRule:edit")
    @Operation(summary = "修改单条告警规则联动记录")
    @Log(express = "修改联动规则")
    public Response<Object> update(@RequestBody @Validated AlarmLinkageRuleDto alarmLinkageRuleDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(alarmLinkageRuleDto.getId()));
        if (alarmLinkageRuleService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(alarmLinkageRuleDto);

        alarmLinkageRuleService.updateById(alarmLinkageRuleDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "alarmLinkageRule:delete")
    @Operation(summary = "批量删除存在的告警规则联动记录")
    @Log(express = "删除联动规则")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (alarmLinkageRuleService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        alarmLinkageRuleService.deleteBatch(ids);

        return Response.ok();
    }
}
